package org.example.servicestudent.util;

import org.springframework.stereotype.Component;

/**
 * 位置工具类
 * 提供地理位置相关的计算功能
 */
@Component
public class LocationUtil {

    // 签到中心点坐标
    private static final double CENTER_LONGITUDE = 121.980254;
    private static final double CENTER_LATITUDE = 39.087939;
    // 签到范围（公里）
    private static final double CHECK_IN_RADIUS = 5.0;

    /**
     * 检查坐标是否在签到范围内
     */
    public static boolean isWithinRange(double latitude, double longitude) {
        double distance = calculateDistance(latitude, longitude, CENTER_LATITUDE, CENTER_LONGITUDE);
        return distance <= CHECK_IN_RADIUS;
    }

    /**
     * 使用Haversine公式计算两点间的距离（公里）
     *
     */
    public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        final int R = 6371; // 地球半径（公里）
        System.out.println(lat1 + " " + lat2 + "   " + lon1 + " " + lon2);
        
        double latDistance = Math.toRadians(lat2 - lat1);
        double lonDistance = Math.toRadians(lon2 - lon1);
        
        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
        
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        
        return R * c;
    }

    /**
     * 获取签到中心点坐标
     */
    public static double[] getCenterCoordinates() {
        return new double[]{CENTER_LATITUDE, CENTER_LONGITUDE};
    }

    /**
     * 获取签到范围（公里）
     */
    public static double getCheckInRadius() {
        return CHECK_IN_RADIUS;
    }

    /**
     * 计算指定坐标到签到中心的距离
     */
    public static double getDistanceToCenter(double latitude, double longitude) {
        return calculateDistance(latitude, longitude, CENTER_LATITUDE, CENTER_LONGITUDE);
    }
}